﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FANN.Net;

namespace ConsoleSQL
{
    public class Test
    {
        public Ann _ann;
        private DataClasses1DataContext data;
        public Test(Ann ann)
        {    data = new DataClasses1DataContext();
            _ann = data.Ann.First(t => t.id == ann.id);
        }


        public void Calc()
        {
           
         

            var file = Path.GetTempFileName();
            var dir = Path.GetRandomFileName();
            File.WriteAllBytes(file, _ann.data.ToArray());
            ZipFile.ExtractToDirectory(file, dir);
            var net = new FANN.Net.NeuralNet();
            net.CreateFromFile(dir + "\\ann.ann");
            File.Delete(file);
            Directory.Delete(dir, true);



            var f = Path.GetTempFileName();
            var dd = Path.GetRandomFileName();
            File.WriteAllBytes(f, _ann.DataSet.data.ToArray());
            ZipFile.ExtractToDirectory(f, dd);
          var  threinData = new TrainingData();
          threinData.ReadTrainFromFile(Directory.GetFiles(dd, "*.dat")[0]);

            File.Delete(f);
            Directory.Delete(dd, true);
           var v= net. TestData(threinData);

            var inp = threinData.Input;
            var outp = threinData.Output;

            var vl = new List<double>();
          
           
            string s = "";
     
            for (var i = 1; i < inp.Length; i++)
            {
              
                var o = net.Run(inp[i]);

                double max = 0;
                var z = 0;
                for (var j = 0; j < o.Length; j++)
                {
                    if (o[j] > max)
                    {
                        max = o[j];
                        z = j;
                    }

                }
                var d = 0;
                for (var j = 0; j <o.Length; j++)
                    if (outp[i][j] == 1)
                        d = j;
             
                if (d == z)
                {
                  
                    vl.Add(max);
                }
             
            }
          
       
            double count = inp.Length;
            for (double i = 0; i <= 1; i += 0.05)
            {
                double vc = 0;
                double ec = 0;
                foreach (var d in vl)
                {
                    if (d > i) vc++;
                }

                s += i + " " + vc/count + ";";
            }

         
        
         


         _ann.test = (vl.Count/count).ToString();
            _ann.testValues = s;
            data.SubmitChanges();
            Console.WriteLine("test " + _ann.name + ": " + _ann.test);
        }
    }
}
